package com.zsoft.test;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class CreateHouseEventServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(CreateHouseEventServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.info("Creating new HouseEvent ");

		String sender = checkNull(req.getParameter("sender"));
		String desc = checkNull(req.getParameter("description"));
		String password = checkNull(req.getParameter("password"));
		Date date = new Date();

		
		HttpSession session = req.getSession(true);
		if(password.length()==3 && desc.toLowerCase().startsWith(password.toLowerCase()))
		{
			Dao.INSTANCE.add(sender, desc, date);
			session.setAttribute("result", "New houseevent created.");
			log.info("New houseevent created");
		}
		else
		{
			session.setAttribute("result", "Error saving houseevent. Invalid password!");
			log.info("Error saving houseevent. Invalid password!");
		}
		
		resp.sendRedirect("/events.jsp");
		//req.getRequestDispatcher("/events.jsp").forward(req, resp);
		/*
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/events.jsp");
		try {
			dispatcher.forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
	}

	private String checkNull(String s) {
		if (s == null) {
			return "";
		}
		return s;
	}
}